package com.example.love_margin.Service.Impl;

import com.example.love_margin.Entity.User;
import com.example.love_margin.Mapper.AdoptMapper;
import com.example.love_margin.Mapper.UserMapper;
import com.example.love_margin.Service.MyService;
import com.example.love_margin.Untils.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class MyServiceImpl implements MyService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    AdoptMapper adoptMapper;


    //登录
    @Override
    public Object addUser(User user) {

        try {
            if(user.getUser_state()!=null){
                userMapper.UpdateUser(user.getUser_picture(),user.getUser_state());
                User jj = userMapper.selectUserMessageByName(user);
                if (jj.getUser_name() != null && jj.getUser_name().length() != 0){
                    int adoptPets = adoptMapper.selectAdoptPets(jj.getUser_id());
                    jj.setAdoptPets(adoptPets);
                    return ResultCode.SUCCESS.result(jj);
                }
            }

        }catch (Exception e){
            System.out.println(e);
        }

        //当用户不存在，自动注册
        int user_id = userMapper.addUserMessage(user);
        if(Integer.toString(user_id).length()!=0&&user_id==1){
            int adoptPets = adoptMapper.selectAdoptPets(user.getUser_id());
            user.setAdoptPets(adoptPets);
            return ResultCode.SUCCESS.result(user);
        }
        try {
            //当用户不存在，创建失败时事务回滚
            int UserID = user.getUser_id();
            userMapper.deleteUserMessage(UserID);
        }catch (Exception e){
            System.out.println(e);
        }
        return ResultCode.SUCCESS.result("登录失败");
    }






}
